<template>
    <div class="products-page">
        <div class="page-header">
            <h2>商品管理</h2>
            <el-button type="primary" @click="showAddDialog">发布商品</el-button>
        </div>

        <!-- 搜索栏 -->
        <el-card class="search-card">
            <el-form :inline="true" :model="searchForm">
                <el-form-item label="商品名称">
                    <el-input v-model="searchForm.name" placeholder="请输入商品名称" />
                </el-form-item>
                <el-form-item label="状态">
                    <el-select v-model="searchForm.status" placeholder="请选择状态">
                        <el-option label="全部" value="" />
                        <el-option label="在售" value="on_sale" />
                        <el-option label="已下架" value="off_sale" />
                        <el-option label="已售出" value="sold" />
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleSearch">搜索</el-button>
                    <el-button @click="resetSearch">重置</el-button>
                </el-form-item>
            </el-form>
        </el-card>

        <!-- 商品列表 -->
        <el-table :data="products" stripe style="margin-top: 20px;">
            <el-table-column type="expand">
                <template #default="{ row }">
                    <div class="product-detail">
                        <el-descriptions :column="2" border>
                            <el-descriptions-item label="商品描述">{{ row.description }}</el-descriptions-item>
                            <el-descriptions-item label="创建时间">{{ row.createdAt }}</el-descriptions-item>
                            <el-descriptions-item label="最后更新">{{ row.updatedAt }}</el-descriptions-item>
                            <el-descriptions-item label="浏览次数">{{ row.views }}</el-descriptions-item>
                        </el-descriptions>
                    </div>
                </template>
            </el-table-column>
            <el-table-column prop="name" label="商品名称" min-width="200" />
            <el-table-column prop="price" label="价格" width="120">
                <template #default="{ row }">
                    ¥{{ row.price }}
                </template>
            </el-table-column>
            <el-table-column prop="stock" label="库存" width="100" />
            <el-table-column prop="status" label="状态" width="100">
                <template #default="{ row }">
                    <el-tag :type="row.status === 'on_sale' ? 'success' : 'info'">
                        {{ row.status === 'on_sale' ? '在售' : '下架' }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="200" fixed="right">
                <template #default="{ row }">
                    <el-button-group>
                        <el-button size="small" type="primary" @click="editProduct(row)">编辑</el-button>
                        <el-button size="small" :type="row.status === 'on_sale' ? 'warning' : 'success'"
                            @click="toggleProductStatus(row)">
                            {{ row.status === 'on_sale' ? '下架' : '上架' }}
                        </el-button>
                        <el-button size="small" type="danger" @click="deleteProduct(row)">删除</el-button>
                    </el-button-group>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination">
            <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :total="total"
                :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next" @size-change="handleSizeChange"
                @current-change="handleCurrentChange" />
        </div>

        <!-- 添加/编辑商品对话框 -->
        <el-dialog v-model="dialogVisible" :title="editingProduct ? '编辑商品' : '发布商品'" width="60%">
            <el-form ref="productForm" :model="productForm" :rules="rules" label-width="100px">
                <el-form-item label="商品名称" prop="name">
                    <el-input v-model="productForm.name" />
                </el-form-item>
                <el-form-item label="商品价格" prop="price">
                    <el-input-number v-model="productForm.price" :min="0" :precision="2" />
                </el-form-item>
                <el-form-item label="商品库存" prop="stock">
                    <el-input-number v-model="productForm.stock" :min="0" :precision="0" />
                </el-form-item>
                <el-form-item label="商品描述" prop="description">
                    <el-input v-model="productForm.description" type="textarea" :rows="4" />
                </el-form-item>
                <el-form-item label="商品图片" prop="images">
                    <el-upload action="/api/file/upload/image" :data="{ type: 'product' }" :on-success="handleUploadSuccess"
                        :on-remove="handleUploadRemove" :file-list="uploadedFileList" list-type="picture-card">
                        <el-icon>
                            <Plus />
                        </el-icon>
                    </el-upload>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="submitForm">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getImageUrl } from '@/utils/image'

// 搜索表单
const searchForm = reactive({
    name: '',
    status: ''
})

// 商品列表数据
const products = ref([
    {
        id: 1,
        name: '二手笔记本电脑',
        price: 2999,
        stock: 1,
        status: 'on_sale',
        description: '9成新笔记本电脑，性能良好',
        createdAt: '2024-04-07',
        updatedAt: '2024-04-07',
        views: 156
    }
])

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(100)

// 表单相关
const dialogVisible = ref(false)
const editingProduct = ref(null)
const productForm = reactive({
    name: '',
    price: 0,
    stock: 1,
    description: '',
    images: []
})
const uploadedFileList = ref([])

// 表单验证规则
const rules = {
    name: [
        { required: true, message: '请输入商品名称', trigger: 'blur' },
        { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
    ],
    price: [
        { required: true, message: '请输入商品价格', trigger: 'blur' }
    ],
    stock: [
        { required: true, message: '请输入商品库存', trigger: 'blur' }
    ],
    description: [
        { required: true, message: '请输入商品描述', trigger: 'blur' },
        { min: 10, max: 500, message: '长度在 10 到 500 个字符', trigger: 'blur' }
    ]
}

// 搜索方法
const handleSearch = () => {
    // TODO: 实现搜索逻辑
    console.log('搜索条件:', searchForm)
}

// 重置搜索
const resetSearch = () => {
    searchForm.name = ''
    searchForm.status = ''
    handleSearch()
}

// 分页方法
const handleSizeChange = (val: number) => {
    pageSize.value = val
    handleSearch()
}

const handleCurrentChange = (val: number) => {
    currentPage.value = val
    handleSearch()
}

// 显示添加对话框
const showAddDialog = () => {
    editingProduct.value = null
    Object.assign(productForm, {
        name: '',
        price: 0,
        stock: 1,
        description: '',
        images: []
    })
    dialogVisible.value = true
}

// 编辑商品
const editProduct = (row: any) => {
    editingProduct.value = row
    Object.assign(productForm, row)
    dialogVisible.value = true
}

// 切换商品状态
const toggleProductStatus = async (row: any) => {
    try {
        await ElMessageBox.confirm(
            `确定要${row.status === 'on_sale' ? '下架' : '上架'}该商品吗？`
        )
        // TODO: 调用API更新商品状态
        row.status = row.status === 'on_sale' ? 'off_sale' : 'on_sale'
        ElMessage.success('操作成功')
    } catch {
        // 用户取消操作
    }
}

// 删除商品
const deleteProduct = async (row: any) => {
    try {
        await ElMessageBox.confirm('确定要删除该商品吗？', '警告', {
            type: 'warning'
        })
        // TODO: 调用API删除商品
        const index = products.value.findIndex(item => item.id === row.id)
        if (index > -1) {
            products.value.splice(index, 1)
        }
        ElMessage.success('删除成功')
    } catch {
        // 用户取消操作
    }
}

// 上传相关方法
const handleUploadSuccess = (response: any, file: any, fileList: any) => {
    if (response.code === 200 && response.data && response.data.filename) {
        productForm.images.push(response.data.filename)
        uploadedFileList.value.push({
            name: response.data.filename,
            url: getImageUrl(response.data.filename, response.data.type)
        })
        ElMessage.success('图片上传成功')
    } else {
        ElMessage.error(response.message || '图片上传失败')
        const internalFile = fileList.find(f => f.uid === file.uid)
        if (internalFile) {
            const index = fileList.indexOf(internalFile)
            fileList.splice(index, 1)
        }
        const displayFileIndex = uploadedFileList.value.findIndex(f => f.uid === file.uid || f.name === file.name)
        if (displayFileIndex !== -1) {
            uploadedFileList.value.splice(displayFileIndex, 1)
        }
    }
}

const handleUploadRemove = (file: any, fileList: any) => {
    const filenameToRemove = file.name || (file.response && file.response.data && file.response.data.filename)
    if (filenameToRemove) {
        const indexInForm = productForm.images.indexOf(filenameToRemove)
        if (indexInForm !== -1) {
            productForm.images.splice(indexInForm, 1)
        }
    }
    const indexInDisplay = uploadedFileList.value.findIndex(f => f.name === filenameToRemove || f.url === file.url)
    if (indexInDisplay !== -1) {
        uploadedFileList.value.splice(indexInDisplay, 1)
    }
    ElMessage.info('图片已移除')
}

// 提交表单
const submitForm = async () => {
    // TODO: 实现表单提交逻辑
    if (editingProduct.value) {
        // 更新商品
        const index = products.value.findIndex(item => item.id === editingProduct.value.id)
        if (index > -1) {
            products.value[index] = { ...products.value[index], ...productForm }
        }
    } else {
        // 添加商品
        products.value.push({
            id: Date.now(),
            ...productForm,
            status: 'on_sale',
            createdAt: new Date().toISOString().split('T')[0],
            updatedAt: new Date().toISOString().split('T')[0],
            views: 0
        })
    }
    dialogVisible.value = false
    ElMessage.success(editingProduct.value ? '更新成功' : '添加成功')
}
</script>

<style scoped>
.products-page {
    padding: 20px;
}

.page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
}

h2 {
    margin: 0;
    font-size: 24px;
    color: #333;
}

.search-card {
    margin-bottom: 20px;
}

.product-detail {
    padding: 20px;
}

.pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
}

:deep(.el-upload--picture-card) {
    width: 100px;
    height: 100px;
    line-height: 100px;
}
</style>